<template>
  <div id="container" v-if="goodsDetail[0]">
    <div class="pro_detail">
      <div class="pro_img">
        <div class="tb_booth">
          <img :src="goodsDetail[0].thumb_url" class="pro_middle_img" />
        </div>
      </div>
      <div class="pro_meg">
        <div class="pro_meg_hd">
          <h1>{{ goodsDetail[0].goods_name }}</h1>
        </div>
        <div class="pro_meg_price">
          <dl>
            <dt>促销价</dt>
            <dd>
              <div class="promo_price">
                <span class="tm-price">{{ goodsDetail[0].price | moneyFormat }}</span>
                <b>优惠促销</b>
              </div>
            </dd>
          </dl>
          <dl>
            <dt>市场价</dt>
            <dd class="nor_price">{{ goodsDetail[0].price * 10 | moneyFormat }}</dd>
          </dl>
          <dl>
            <dt>本店优惠</dt>
            <dd class="baoyou">包邮</dd>
          </dl>
          <dl>
            <dt class="sale_tip">{{ goodsDetail[0].sales_tip }}</dt>
          </dl>
          <dl>
            <dt>服务承诺</dt>
            <dd>
              <div class="services">
                <span>正品保证</span>
                <span>极速退货</span>
              </div>
            </dd>
          </dl>
        </div>
        <div class="pro_meg_deliver">
          <dl>
            <dt>运费</dt>
            <dd class="address">福建福州&nbsp;&nbsp;至&nbsp;&nbsp;福建福州&nbsp;&nbsp;&nbsp;快递:0.00</dd>
          </dl>
        </div>
        <div class="pro_meg_console">
          <dl class="tb-sku">
            <dt class="number">数量</dt>
            <dd>
              <div class="item-amount">
                <el-input-number v-model="shopNum" :min="1" :max="goodsDetail[0].counts"></el-input-number>
              </div>
              <div class="acount">
                <span>库存</span><em>{{ goodsDetail[0].counts }}</em><span>件</span>
              </div>
            </dd>
          </dl>
          <div class="shopping_car">
            <el-button type="primary" @click.prevent="dealWithCellBtnClick(goodsDetail[0])"
              class="add_car">加入购物车</el-button>
            <el-button type="danger" @click="confirmBuy(goodsDetail[0])" class="buy_now">立即购买</el-button>
          </div>
        </div>
      </div>
    </div>
    <div class="pro_comment">
      <h3>商品评价</h3>
      <div v-if="goodsComment.length">
        <div class="media" v-for="(comment, index) in goodsComment" :key="index">
          <div class="media-body">
            <h6 class="media-heading" v-if="comment.user_nickname">用户:&nbsp;{{ comment.user_nickname }}</h6>
            <h6 class="media-heading" v-else>用户:&nbsp;{{ comment.user_name | nameFormat }}</h6>
            <span>评论:</span>&nbsp;{{ comment.comment_detail }}
            <el-rate v-model="comment.comment_rating" disabled show-score text-color="#ff9900"></el-rate>
          </div>
        </div>
      </div>
      <div class="media" v-else>
        <div class="media-body">
          本商品暂无评价
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { addGoodsToCart, updateStock } from './../../api/index'; // Import the new API method
import { MessageBox, Message } from 'element-ui';
import { mapState } from 'vuex';

export default {
  data() {
    return {
      currentGoodsId: 0,
      shopNum: 1,
    };
  },
  computed: {
    ...mapState(['goodsDetail', 'userInfo', 'goodsComment'])
  },
  created() {
    this.currentGoodsId = Number(this.$route.params.id);
    this.$store.dispatch('reqGoodsDetail', {
      goodsNo: this.currentGoodsId
    });
    this.$store.dispatch('reqGoodsComment', {
      goodsId: this.currentGoodsId
    });
  },
  mounted() {
    window.scrollTo(0, 0); // Ensure the scroll position is at the top
  },
  watch: {
    $route() {
      this.currentGoodsId = Number(this.$route.params.id);
      this.$store.dispatch('reqGoodsDetail', {
        goodsNo: this.currentGoodsId
      });
      this.$store.dispatch('reqGoodsComment', {
        goodsId: this.currentGoodsId
      });
      // 请求当前用户信息
      this.$store.dispatch('getUserInfo');
      window.scrollTo(0, 0); // Ensure the scroll position is at the top
    }
  },
  methods: {
    async dealWithCellBtnClick(goods) {
      if (!this.userInfo.id) {
        this.$message.error('请先登录');
        // this.$router.push('/login');
        return;
      }
      if (this.userInfo.user_name) {
        let result = await addGoodsToCart(this.userInfo.id, goods.goods_id, goods.short_name, goods.thumb_url, goods.price, this.shopNum, goods.counts);
        if (result.success_code === 200) {
          MessageBox({
            type: 'success',
            message: result.message,
            showClose: true,
          });
          let user_id = this.userInfo.id;
          // 请求商品数据
          this.$store.dispatch('reqCartsGoods', { user_id });
          this.shopNum = 1;
        }
      }
    },
    async confirmBuy(goods) {
      if (!this.userInfo.id) {
        this.$message.error('请先登录');
        // this.$router.push('/login');
        return;
      }

      MessageBox.confirm('确认购买该商品吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.buyGoods(goods);
      }).catch(() => {
        Message({
          type: 'info',
          message: '已取消购买'
        });
      });
    },
    async buyGoods(goods) {
      const order = {
        user_id: this.userInfo.id,
        items: [{
          goods_id: goods.goods_id,
          goods_name: goods.goods_name,
          thumb_url: goods.thumb_url,
          price: goods.price,
          buy_count: this.shopNum,
          counts: goods.counts
        }],
        totalAmount: this.shopNum,
        totalPrice: goods.price * this.shopNum,
        date: new Date().toLocaleString()
      };

      try {
        await this.$store.dispatch('createOrder', order);

        // Update the stock
        await updateStock(goods.goods_id, this.shopNum);

        Message({
          type: 'success',
          message: '购买成功'
        });
        this.shopNum = 1; // 重置购买数量

        // Update the goods detail after stock change
        this.$store.dispatch('reqGoodsDetail', { goodsNo: this.currentGoodsId });

      } catch (error) {
        Message({
          type: 'error',
          message: '购买失败'
        });
      }
    }
  }
}
</script>

<style scoped>
#container {
  background: #f7f7f7;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.pro_detail {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 40px;
}

.pro_img,
.pro_meg {
  flex: 1 1 50%;
}

.pro_img {
  display: flex;
  flex: 3;
  align-items: center;
  justify-content: center;
  border: 1px solid #ccc;
  border-radius: 10px;
  overflow: hidden;
}

.tb_booth {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.tb_booth img {
  max-width: 100%;
  max-height: 100%;
}

.pro_meg {
  background: #fff;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pro_meg_hd h1 {
  font-size: 24px;
  color: #333;
  margin-bottom: 20px;
}

.pro_meg_price,
.pro_meg_deliver,
.pro_meg_console {
  margin-bottom: 20px;
}

.pro_meg_price dl,
.pro_meg_deliver dl,
.pro_meg_console dl {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.pro_meg_price dt,
.pro_meg_deliver dt,
.pro_meg_console dt {
  font-weight: bold;
  color: #666;
}

.promo_price {
  margin-left: 40px;
  margin-top: 10px;
  display: flex;
  align-items: center;
}

.promo_price .tm-price {
  font-size: 28px;
  color: #f56c6c;
  margin-right: 10px;
}

.nor_price {
  margin-top: 5px;
  margin-left: 40px;
  text-decoration: line-through;
  color: #999;
}

.sale_tip {
  color: #f56c6c;
  font-weight: bold;
}

.pro_meg_deliver dd {
  color: #333;
}

.services {
  margin-left: 40px;
  margin-top: 5px;
}

.services span {
  margin-right: 10px;
}

.item-amount {
  margin-left: 40px;
  margin-top: 5px;
  display: flex;
  align-items: center;
}

.shopping_car {
  margin-left: 70px;
  display: flex;
  gap: 20px;
}

.add_car,
.buy_now {
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  font-size: 16px;
  border-radius: 5px;
}

.pro_comment {
  background: #fff;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pro_comment h3 {
  font-size: 20px;
  margin-bottom: 20px;
}

.pro_comment .media {
  padding: 10px 0;
  border-top: 1px solid #eee;
}

.pro_comment .media:first-child {
  border-top: none;
}

.pro_comment .media-heading {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 5px;
}

.pro_comment .el-rate {
  margin-left: 10px;
}

.baoyou {
  margin-left: 40px;
  margin-top: 5px;
}

.address {
  margin-left: 40px;
  margin-top: 5px;
}

.number {
  margin-bottom: 25px;
}

.acount {
  margin-left: 40px;
  margin-top: 10px;
}
</style>
